package MyGO.utils.PingYinUtils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;


public class PinyinUtils {
    /**
     * 将汉字字符串转换为拼音助记码
     *
     * @param chinese 汉字字符串
     * @return 拼音助记码
     */
    public static String getPinyinAcronym(String chinese) {
        StringBuilder acronym = new StringBuilder();
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);

        for (char ch : chinese.toCharArray()) {
            if (Character.toString(ch).matches("[\\u4E00-\\u9FA5]")) { // 判断是否是汉字
                try {
                    String[] pinyins = PinyinHelper.toHanyuPinyinStringArray(ch, format);
                    if (pinyins != null && pinyins.length > 0) {
                        acronym.append(pinyins[0].charAt(0));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                acronym.append(ch);
            }
        }

        return acronym.toString().toUpperCase();
    }

}
